/**
 * 案件选择器组件
 * 用于在各个模块中统一调用案件选择功能
 */
window.CaseSelector = {
    /**
     * 打开案件选择模态框
     * @returns {Promise<{id: number, name: string}|null>} 返回选中的案件信息，取消则返回 null
     */
    selectCase: async function () {
        try {
            // 从主进程中获取案件列表
            const cases = await window.electronAPI.case.getAll();

            if (!cases || cases.length === 0) {
                alert('没有找到任何案件，请先在首页创建一个案件');
                return null;
            }

            // 创建选择案件的模态框
            return new Promise((resolve) => {
                const modalId = `select-case-modal-${Date.now()}`;
                let selectedCaseId = null;

                // 生成案件列表HTML
                let casesHtml = '';
                cases.forEach(c => {
                    casesHtml += `
          <div class="case-option" 
               style="padding: 10px; border: 1px solid #ddd; margin: 5px 0; cursor: pointer; border-radius: 4px; transition: background 0.2s;"
               data-id="${c.id}"
               onclick="window.CaseSelector._selectOption('${modalId}', this, '${c.id}')">
            <div style="display:flex; justify-content:space-between; align-items:center;">
              <strong>${c.case_name}</strong>
              <span class="status-tag" style="font-size:0.8em; padding:2px 6px; background:#e6f7ff; color:#1890ff; border-radius:4px;">${c.case_status}</span>
            </div>
            <div style="color: #999; font-size: 0.85em; margin-top:5px;">
              编号: ${c.case_number || '无'} | 创建: ${new Date(c.created_time).toLocaleString()}
            </div>
          </div>`;
                });

                const modalHtml = `
          <div id="${modalId}" style="position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999; display:flex; justify-content:center; align-items:center;">
            <div style="background:white; padding:20px; border-radius:8px; width:90%; max-width:600px; max-height:80vh; overflow-y:auto; box-shadow:0 4px 12px rgba(0,0,0,0.15); animation: fadeIn 0.2s;">
              <h3 style="margin-top:0; margin-bottom:15px; font-size:1.1rem; border-bottom:1px solid #eee; padding-bottom:10px;">请选择案件</h3>
              <div id="cases-list-${modalId}" style="max-height:400px; overflow-y:auto;">
                ${casesHtml}
              </div>
              <div style="display:flex; justify-content:flex-end; gap:10px; margin-top:20px; padding-top:10px; border-top:1px solid #eee;">
                <button id="${modalId}-cancel" class="btn-secondary">取消</button>
                <button id="${modalId}-confirm" class="btn-primary" disabled>确定</button>
              </div>
            </div>
          </div>
        `;

                document.body.insertAdjacentHTML('beforeend', modalHtml);

                const modal = document.getElementById(modalId);
                const btnCancel = document.getElementById(`${modalId}-cancel`);
                const btnConfirm = document.getElementById(`${modalId}-confirm`);

                // 内部清理函数
                const close = (result) => {
                    modal.remove();
                    // 清理可能存在的全局引用（如果有的话）
                    resolve(result);
                };

                // 绑定事件
                btnCancel.onclick = () => close(null);

                btnConfirm.onclick = () => {
                    // 获取当前选中的ID（通过闭包变量或DOM状态）
                    // 这里我们使用闭包变量 selectedCaseId，它由 _selectOption 更新
                    // 但由于 _selectOption 是全局调用的，我们需要一种方式获取状态
                    // 简单方式：直接查询DOM中选中的元素
                    const selectedEl = document.querySelector(`#cases-list-${modalId} .case-option[data-selected="true"]`);
                    if (selectedEl) {
                        const id = selectedEl.getAttribute('data-id');
                        const selectedCase = cases.find(c => c.id == id);
                        if (selectedCase) {
                            close({ id: selectedCase.id, name: selectedCase.case_name, fullData: selectedCase });
                        } else {
                            close(null);
                        }
                    } else {
                        alert('请选择一个案件');
                    }
                };
            });
        } catch (error) {
            console.error('获取案件列表失败:', error);
            alert('获取案件列表失败: ' + error.message);
            return null;
        }
    },

    /**
     * 内部使用的选项点击处理函数
     * @private
     */
    _selectOption: function (modalId, element, caseId) {
        // 重置所有选项样式
        const container = document.getElementById(`cases-list-${modalId}`);
        if (!container) return;

        const options = container.querySelectorAll('.case-option');
        options.forEach(opt => {
            opt.style.backgroundColor = '';
            opt.style.borderColor = '#ddd';
            opt.removeAttribute('data-selected');
        });

        // 设置选中项样式
        element.style.backgroundColor = '#e6f7ff';
        element.style.borderColor = '#1890ff';
        element.setAttribute('data-selected', 'true');

        // 启用确定按钮
        const btnConfirm = document.getElementById(`${modalId}-confirm`);
        if (btnConfirm) btnConfirm.disabled = false;
    }
};
